package org.springblade.metadata.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.atlas.AtlasClientV2;
import org.apache.atlas.AtlasServiceException;
import org.apache.atlas.model.glossary.AtlasGlossaryTerm;
import org.apache.atlas.model.glossary.relations.AtlasGlossaryHeader;
import org.apache.atlas.model.instance.AtlasRelatedObjectId;
import org.apache.commons.lang3.StringUtils;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.tool.utils.Func;
import org.springblade.metadata.entity.Category;
import org.springblade.metadata.service.AtlasProxyService;
import org.springblade.metadata.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component("gossaryService")
public class GossaryService {
	
	
	@Autowired
	private AtlasProxyService atlasProxyService;
	
	
	@Autowired
	private  ICategoryService  categoryService;
	
	
	public String getGuidByCategaryid(Category c) throws AtlasServiceException {
		if(StringUtils.isBlank(c.getOutCode())) {
			AtlasClientV2  client  = atlasProxyService.get();
			
			AtlasGlossaryTerm glossaryTerm = new AtlasGlossaryTerm();
			glossaryTerm.setName(c.getId().toString());
			AtlasGlossaryHeader anchor = new AtlasGlossaryHeader(atlasProxyService.getGguid());
			glossaryTerm.setAnchor(anchor);
			glossaryTerm = client.createGlossaryTerm(glossaryTerm);
			
			c.setOutCode(glossaryTerm.getGuid());
			categoryService.updateById(c);
		}
		return  c.getOutCode();
	}
	
	public void assignTermToEntities(String termId,String es) throws AtlasServiceException {
		AtlasClientV2  client  = atlasProxyService.get();
		
		List<AtlasRelatedObjectId> relatedObjectIds =new ArrayList<>();
		
		String[] ids = es.split(",");
		
		for(String id :ids) {
			
			AtlasRelatedObjectId  aid = new AtlasRelatedObjectId();
			aid.setGuid(id);
			relatedObjectIds.add(aid
					); 
		}
		client.assignTermToEntities(termId, relatedObjectIds);
	}
	
	public void disAssignTermToEntities(String termId,String es) throws AtlasServiceException {
		AtlasClientV2  client  = atlasProxyService.get();
		
		List<AtlasRelatedObjectId> relatedObjectIds =new ArrayList<>();
		
		String[] ids = es.split(",");
		
		for(String id :ids) {
			
			AtlasRelatedObjectId  aid = new AtlasRelatedObjectId();
			aid.setGuid(id);
			relatedObjectIds.add(aid
					); 
		}
		client.disassociateTermFromEntities(termId, relatedObjectIds);
	}
	
	public boolean remove(String ids) throws AtlasServiceException {
		AtlasClientV2  client  = atlasProxyService.get();
		List<Long>  lls = Func.toLongList(ids);
		
		for (Long id :lls) {
			Category  c  = categoryService.getById(id);
			if(c == null) {
				throw new ServiceException("null");
			}
			
			client.deleteGlossaryTermByGuid(c.getOutCode());
		}
		
		return categoryService.removeCategory(ids);
	}
	
}
